package com.shop.front.controller.pay;

import com.github.wxpay.sdk.WXPayUtil;
import com.shop.front.service.pay.PayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 支付回调
 *
 * @Author Administrator
 * @Date 2023/9/8 15:23
 * @Version 1.0
 */
@RestController
@RequestMapping("/callBack")
public class CallBackController {
    private static Logger logger = LoggerFactory.getLogger(CallBackController.class);


    @Autowired
    PayService payService;

    /**
     * 支付宝回调
     *
     * @param request
     * @param response
     */
    @RequestMapping("/alipayCallback")
    @ResponseBody
    public void callback(HttpServletRequest request, HttpServletResponse response) {

        final Map<String, String> params = convertRequestParamsToMap(request); // 将异步通知中收到的待验证所有参数都存放到map中
        logger.info("支付宝回调，{}", params);
        if ("TRADE_SUCCESS".equals(params.get("trade_status"))) {
            // 处理支付成功逻辑
            try {
               // rechargeService.getAlipayPublicKey(params);
            } catch (Exception e) {
                e.printStackTrace();
                //logger.error("支付宝回调业务处理报错,params:" + params, e);
            }
        } else {
            logger.error("没有处理支付宝回调业务，支付宝交易状态：{},params:{}", params.get("trade_status"), params);
        }
        // 如果签名验证正确，立即返回success，后续业务另起线程单独处理
        // 业务处理失败，可查看日志进行补偿，跟支付宝已经没多大关系。
        printWriStr("success", response);
    }


    /**
     * 微信支付回调
     *
     * @param request
     * @param response
     */
    @RequestMapping("/wxPayCallBack")
    @ResponseBody
    public void wxPayCallBack(HttpServletRequest request, HttpServletResponse response) {
        BufferedReader reader = null;
        try {

            // 读取微信发送的数据
            reader = request.getReader();
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=UTF-8");
            response.setHeader("Access-Control-Allow-Origin", "*");

            String line = "";
            String xmlString = null;

            StringBuffer inputString = new StringBuffer();

            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            xmlString = inputString.toString();
            request.getReader().close();

            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");
            out.flush();
            out.close();

            //字符串转为Map对象
            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(xmlString);
            logger.info("微信回调，{}", xmlToMap);
            //支付成功!
            if ("SUCCESS".equals(xmlToMap.get("return_code")) && "SUCCESS".equals(xmlToMap.get("result_code"))) {
                payService.payNotify(xmlToMap.get("out_trade_no"), xmlToMap.get("transaction_id"));
            }
        } catch (Exception e) {
            // TODO: 2023/6/15   这里补充一下报错日志
            logger.error("微信支付回调:{}", e.getMessage());
            e.printStackTrace();
        }
    }


    /**
     * 将request中的参数转换成Map
     *
     * @param request
     * @return
     */
    private static Map<String, String> convertRequestParamsToMap(HttpServletRequest request) {
        Map<String, String> retMap = new HashMap<>();

        Set<Map.Entry<String, String[]>> entrySet = request.getParameterMap().entrySet();

        for (Map.Entry<String, String[]> entry : entrySet) {
            String name = entry.getKey();
            String[] values = entry.getValue();
            int valLen = values.length;

            if (valLen == 1) {
                retMap.put(name, values[0]);
            } else if (valLen > 1) {
                StringBuilder sb = new StringBuilder();
                for (String val : values) {
                    sb.append(",").append(val);
                }
                retMap.put(name, sb.toString().substring(1));
            } else {
                retMap.put(name, "");
            }
        }

        return retMap;
    }

    /**
     * @param str      设定文件
     * @param response 返回类型
     */
    public static void printWriStr(String str, HttpServletResponse response) {
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.print(str);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }






}
